package com.jxtti.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.jxtti.entity.ArticleCategory;
import com.jxtti.model.User;
import com.jxtti.service.ArticleCategoryService;
import com.jxtti.utils.AuthUtil;
import com.jxtti.utils.ExceptionUtil;



@Controller
@RequestMapping("/ArticleCategory") 
public class ArticleCategoryController {
	private final static Logger log= Logger.getLogger(ArticleCategoryController.class);
	
	@Autowired //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
	private ArticleCategoryService  articleCategoryService; 
	
	@InitBinder  //初始化数据的时候，进行数据类型转换，String类型转为Date类型
    public void initBinder(WebDataBinder binder) {     
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");     
        dateFormat.setLenient(false);     
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));//true:���������ֵ��false:����Ϊ��ֵ 
    }
	
	
	/**
	 * 通过父节点ID获取
	 * 
	 * @param data
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/findByPid", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> findByPid(
			@RequestParam Map<String, Object> data, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {			
			data.put("visible", "1");
			System.out.println(AuthUtil.getUserInfo(request).getRoleId());
			if(AuthUtil.getUserInfo(request).getRoleId()== null){ //还未添加网站角色
				result.put("success", false);
				result.put("error", "抱歉，你没有权限，请联系网站管理员！");
			}else{
				data.put("roleId", AuthUtil.getUserInfo(request).getRoleId()); //获取角色id
				List<ArticleCategory>  menuList= articleCategoryService.findByPid(data);			
				result.put("menuList", menuList);
				result.put("success", true);
			}			
		} catch (Exception e) {
			result.put("success", false);
			result.put("error", ExceptionUtil.createStackTrackMessage(e));			
			e.printStackTrace();
		}
		return result;
	}

	
	@RequestMapping(value = "/listInterface")
	@ResponseBody
	public ModelAndView listInterface(@RequestParam Map<String, Object> data,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			mav.addObject("data", data);
			mav.setViewName("/pages/Admin/Site/Article/CategoryList.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
	
	@RequestMapping(value = "/getCategoryInterface")
	@ResponseBody
	public ModelAndView getCategoryInterface(@RequestParam Map<String, Object> data,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			mav.addObject("data", data);
			mav.setViewName("/pages/Admin/Site/Article/getArticleCy.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
	
	/**
	 * 返回easyui 树结构
	 * , method = RequestMethod.POST
	 * @param data
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getEasyUiTree")
	@ResponseBody
	public List<Map<String, Object>> getEasyUiTree(
			@RequestParam Map<String, String> data, HttpServletRequest request) {
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		try {	
			//判断是否超级管理员		
			User userInfo = AuthUtil.getUserInfo(request);		
			/*
			if(userInfo.getDistrictId()==null || userInfo.getDistrictId().equals("0")){ //非超管
				data.put("fk_orgId",userInfo.getOrgId().toString()); //非超级管理员 加上权限
				if(null == data.get("level")){ //根节点				
					data.put("isRoot","true"); 				
				}			
			}else if (null == data.get("parentID")) { //超级管理员不加权限
				data.put("parentID", "0");			
			}	
			*/
			
			//noAdmin 管理员是否失效
			if(data.get("noAdmin")==null){
				if(userInfo.getDistrictId()==null || userInfo.getDistrictId().equals("0")){ //非管理员
					data.put("fk_orgId",userInfo.getOrgId().toString()); //非超级管理员 加上权限							
					if(null == data.get("level")){ //根节点				
						data.put("isRoot","true"); 				
					}							
				}else if (null == data.get("parentID")) { //超级管理员不加权限
					data.put("parentID", "0");			
				}
			}else if(data.get("noAdmin")!=null && data.get("noAdmin").equals("yes")){ 		 
				if(userInfo.getRoleId()!=com.jxtti.utils.Constants.AdminRole){//非超管
					data.put("fk_orgId",userInfo.getOrgId().toString()); //非超级管理员 加上权限								
					if(null == data.get("level")){ //根节点				
						data.put("isRoot","true"); 				
					}							
				}else if (null == data.get("parentID")) { //超级管理员不加权限
					data.put("parentID", "0");			
				}
			}
			
			result = articleCategoryService.getEasyUiTree(data);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	
	@RequestMapping(value = "/getEasyUiTreeForSelect")
	@ResponseBody
	public List<Map<String, Object>> getEasyUiTreeForSelect(
			@RequestParam Map<String, String> data, HttpServletRequest request) {
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		try {
			//判断是否超级管理员		
			User userInfo = AuthUtil.getUserInfo(request);
			
			if(null != data.get("isContribute")&&data.get("isContribute").equals("1")){//县级投稿 不分权限
				data.put("is_contribute", "1");					
			}else if(data.get("noAdmin")!=null && data.get("noAdmin").equals("yes")){ //普通管理员无效
				if(userInfo.getRoleId()!=com.jxtti.utils.Constants.AdminRole){ //是否超管
					data.put("fk_orgId",userInfo.getOrgId().toString()); //非超级管理员 加上权限
					if(null == data.get("level")){ //根节点				
						data.put("isRoot","true"); 				
					}					
				}else if (null == data.get("parentID")) { //超级管理员不加权限
					data.put("parentID", "0");	
					Map<String, Object> rootnode = new HashMap<String, Object>();					
					rootnode.put("id", "0");				
					rootnode.put("text", "根节点");
					Map<String, Object> attrNode = new HashMap<String, Object>();							
					attrNode.put("levelID", "0");//级别
					attrNode.put("fk_orgId",null);//所属科室 为空
					rootnode.put("attributes",attrNode);				
					result.add(rootnode);
				}				
			}else if(data.get("noAdmin")==null){  //管理员有效 
				if(userInfo.getDistrictId()==null || userInfo.getDistrictId().equals("0")){ //非管理员
					data.put("fk_orgId",userInfo.getOrgId().toString()); //非超级管理员 加上权限
					if(null == data.get("level")){ //根节点				
						data.put("isRoot","true"); 				
					}	
				}else if (null == data.get("parentID")) { //超级管理员不加权限
					data.put("parentID", "0");	
					Map<String, Object> rootnode = new HashMap<String, Object>();					
					rootnode.put("id", "0");				
					rootnode.put("text", "根节点");
					Map<String, Object> attrNode = new HashMap<String, Object>();							
					attrNode.put("levelID", "0");//级别			
					attrNode.put("fk_orgId",null);//所属科室 为空
					rootnode.put("attributes",attrNode);				
					result.add(rootnode);
				}	
			}
			
			/*	
			if(userInfo.getRoleId()!=com.jxtti.utils.Constants.AdminRole){ //非超管
				
				data.put("fk_orgId",userInfo.getOrgId().toString()); //非超级管理员 加上权限
				if(null == data.get("level")){ //根节点				
					data.put("isRoot","true"); 				
				}			
			}else if (null == data.get("parentID")) { //超级管理员不加权限
				data.put("parentID", "0");	
				Map<String, Object> rootnode = new HashMap<String, Object>();					
				rootnode.put("id", "0");				
				rootnode.put("text", "根节点");
				Map<String, Object> attrNode = new HashMap<String, Object>();							
				attrNode.put("levelID", "0");//级别			
				attrNode.put("fk_orgId",null);//所属科室 为空
				rootnode.put("attributes",attrNode);				
				result.add(rootnode);
			}*/
			
			List<Map<String, Object>> resultSub = articleCategoryService.getEasyUiTreeForSelect(data);
			result.addAll(resultSub);			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}	
	
	
	/**
	 * 获取文章类目 的z-tree结构  bff
	 * 
	 * @param data
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getzTreeNodes")
	@ResponseBody
	public List<ArticleCategory> getzTreeNodes(
			@RequestParam Map<String, String> data, HttpServletRequest request) {
		List<ArticleCategory> resultList=new ArrayList<ArticleCategory>();		
		//判断是否超级管理员		
		User userInfo = AuthUtil.getUserInfo(request);
		//noAdmin 管理员是否失效
		if(data.get("noAdmin")==null){
			if(userInfo.getDistrictId()==null || userInfo.getDistrictId().equals("0")){ //非管理员
				data.put("fk_orgId",userInfo.getOrgId().toString()); //非超级管理员 加上权限
				data.put("andiscon","-99");// 在加上 所有科室				
				if(null == data.get("level")){ //根节点				
					data.put("isRoot","true"); 				
				}							
			}else if (null == data.get("parentID")) { //超级管理员不加权限
				data.put("parentID", "0");			
			}
		}else if(data.get("noAdmin")!=null && data.get("noAdmin").equals("yes")){ 		 
			if(userInfo.getRoleId()!=com.jxtti.utils.Constants.AdminRole){//非超管
				data.put("fk_orgId",userInfo.getOrgId().toString()); //非超级管理员 加上权限
				data.put("andiscon","-99");// 在加上 所有科室				
				if(null == data.get("level")){ //根节点				
					data.put("isRoot","true"); 				
				}							
			}else if (null == data.get("parentID")) { //超级管理员不加权限
				data.put("parentID", "0");			
			}
		}
				
				
		resultList= articleCategoryService.getzTreeNodes(data);			
		return resultList;
	}
	
	
	/**
	 * 查询所有数据,
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/queryAll")
	@ResponseBody
	public List<ArticleCategory> queryTCityAQIWriteAll(@RequestParam Map<String, Object> data,
			HttpServletRequest request,	HttpServletResponse response) throws Exception{
		
		data.put("is_deleted", "0");		
		List<ArticleCategory>  ArticleCategory= articleCategoryService.queryAll(data);
		return ArticleCategory;
	}
	
	/**
	 * 点击添加跳转到增加界面
	 * 
	 * @param data
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/addInterface")
	@ResponseBody
	public ModelAndView addInterface(@RequestParam Map<String, Object> data,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			mav.addObject("data", data);
			mav.setViewName("/pages/Admin/Site/Article/CategoryEdit.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}	
	
	/**
	 * 添加或修改数据
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/save")
	@ResponseBody	
	public Map<String,Object> save(@RequestParam Map<String, Object> data,
			ArticleCategory  articleCategory, HttpServletRequest request,	HttpServletResponse response) throws Exception{		
		ModelAndView mav = new ModelAndView();
		try {							
			int exeCount = articleCategoryService.add(articleCategory);
			if (exeCount > 0) {
				data.put("success", true);
			} else {
				data.put("success", false);
			}
		} catch (Exception e) {
			data.put("success", false);
			data.put("error", ExceptionUtil.createStackTrackMessage(e));
			e.printStackTrace();
		}
		return data;
	}	
	
	
	/**
	 * 点击修改跳转到增加界面
	 * 
	 * @param data
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/updateInterface")
	@ResponseBody
	public ModelAndView updateInterface(@RequestParam Map<String, Object> data,
			HttpServletRequest request,ArticleCategory  articleCategory,
			HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			articleCategory = articleCategoryService.queryById(articleCategory);		
			data.put("articleCategory", articleCategory);
			mav.addObject("data", data);
			mav.setViewName("/pages/Admin/Site/Article/CategoryEdit.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
		
	/**
	 * 修改信息
	 * 
	 * @param data
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> update(@RequestParam Map<String, Object> data,
			ArticleCategory  articleCategory, HttpServletRequest request,
			HttpServletResponse response) {
		try {			
			int exeCount;
			if(data.get("type")!=null&&data.get("type").equals("upDown")){ //上移下移
				ArticleCategory tArticleCategory=articleCategoryService.queryById(articleCategory);
				tArticleCategory.setSortID(articleCategory.getSortID());
				exeCount = articleCategoryService.update(tArticleCategory);
			}else{
				exeCount = articleCategoryService.update(articleCategory);
			}
			
			if (exeCount > 0) {
				data.put("success", true);
			} else {
				data.put("success", false);
			}
		} catch (Exception e) {
			data.put("success", false);
			data.put("error", ExceptionUtil.createStackTrackMessage(e));
			e.printStackTrace();
		}
		return data;
	}
	
	
	/**
	 * 删除信息
	 * 
	 * @param data
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Map<String, Object> delete(@RequestParam Map<String, Object> data,
			HttpServletRequest request,	HttpServletResponse response) {
		try {			
			String[] idArr=data.get("ids").toString().split(",");
			for(String id:idArr){
				ArticleCategory  ArticleCategory=new ArticleCategory();
				ArticleCategory.setId(Integer.parseInt(id));											
				int exeCount=articleCategoryService.delete(ArticleCategory);
				if (exeCount > 0) {
					data.put("success", true);
				} else {
					data.put("success", false);
				}
			}
		} catch (Exception e) {
			data.put("success", false);
			data.put("error", ExceptionUtil.createStackTrackMessage(e));
			e.printStackTrace();
		}
		return data;
	}
	
}
